package com.ai.web.controller;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ai.web.cache.Constants;
import com.ai.web.sendreq.RequestApp;
import com.ai.web.service.*;
import com.ai.web.util.JsonUtil;
import com.ai.web.weixin.message.response.TextMessage;
import com.ai.web.weixin.message.util.MessageUtil;
import com.tiny.persistence.domain.WxMenu;
import com.tiny.persistence.domain.WxRoleMenu;
import com.tiny.persistence.domain.WxUser;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ai.web.util.WorkStatus;
import com.ai.web.vo.ICashDeviceV;
import com.ai.web.vo.RepairV;
import com.tiny.persistence.domain.Repair;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/weixin")
public class WeixinController extends BaseController {
	 
	private static Logger logger = Logger.getLogger(WeixinController.class);

	@Autowired
	private RepairService repairService;
	@Autowired
	private CommentRepairService commentRepairService;
	@Autowired
	private CompanyProfileService companyProfileService;
	@Autowired
	private ICashDeviceService iCashDeviceService;
	@Autowired
    private WxUserService wxUserService;
    @Autowired
    private WxRoleMenuService wxRoleMenuService;

	@RequestMapping(value = "/company")
	public String company(Model model) {
    	try {
			model.addAttribute("companyProfile", companyProfileService.getCompany());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "weixin/company";
	}
	
	@RequestMapping(value = "/repair")
	public String repair(@RequestParam String code, Model model) throws  Exception {
        logger.info("repairList code:"+code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constants.APPID+"&secret="+Constants.SECRET+"&code="+code+"&grant_type=authorization_code";
        String responseEntityContent = RequestApp.request(url, null);
        logger.info("content:"+responseEntityContent);
        HashMap content = JsonUtil.fromJson(responseEntityContent, HashMap.class);
        logger.info("responseEntityContent map:"+content);
        String openId = "";
        if(content.get("openid") == null){
            return "weixin/error";
        }else{
            openId = String.valueOf(content.get("openid"));
            WxUser user =  wxUserService.getByOpenId(openId);
            if(user == null){
                return "weixin/error";
            }
            List<WxRoleMenu> list = wxRoleMenuService.findSelectedMenuList(user.getWxRole().getId());
            logger.info("[Click WxRoleMenu] " + list);
            if(list == null || list.size() == 0){
                return "weixin/error";
            }
            boolean flag = false;
            for(WxRoleMenu wxRoleMenu:list){
                if(wxRoleMenu.getWxMenuId() == 4){
                    flag = true;
                    break;
                }
            }
            if(!flag){
                return "weixin/error";
            }
        }
        model.addAttribute("openId", openId);
		return "weixin/repair";
	}

	@RequestMapping(value = "/repair/add")
	public String repairAdd(@RequestParam String openId, Model model) {
		model.addAttribute("openId", openId);
		return "weixin/repair-add";
	}

	@RequestMapping(value = "/repair/add/{serialNumber}")
	public String repairAddTemplate(@RequestParam(required=false) String openId, @PathVariable("serialNumber") String serialNumber, Model view) throws Exception {
		ICashDeviceV iCashDevice = iCashDeviceService.get(serialNumber);
		logger.info("ICashDeviceV add:"+iCashDevice);
		view.addAttribute("openId", openId);
		view.addAttribute("serialNumber", serialNumber);
		view.addAttribute("manufacturer", iCashDevice.getManufacturer());
		view.addAttribute("model", iCashDevice.getModel());
		view.addAttribute("maintenanceUser", iCashDevice.getMaintenanceUser());
		view.addAttribute("machineAddress", iCashDevice.getMachineAddress());
		view.addAttribute("maintenancePhone", iCashDevice.getMaintenancePhone());
		view.addAttribute("contact", iCashDevice.getContact());
		view.addAttribute("contactPhone", iCashDevice.getContactPhone());
		view.addAttribute("orgId", iCashDevice.getOrgId());
		view.addAttribute("orgName", iCashDevice.getOrgName());
		logger.info("repairAddTemplate:"+view);
		return "weixin/repair-add-template";
	}

    @RequestMapping(value = "/repair/list/{openId}")
    public String repairListByOpenId(@PathVariable("openId") String openId,  Model model) throws Exception{
        logger.info("getListByOpenId openId:"+openId);
        List<Repair> list = repairService.getListByOpenId(openId);
        logger.info("getListByOpenId openId:"+list);
        List<RepairV> repairs = new ArrayList<RepairV>();
        for(Repair repair:list){
            RepairV repairV = new RepairV();
            BeanUtils.copyProperties(repair, repairV);
            repairV.setStatusStr(WorkStatus.getName(repairV.getStatus()));
            repairs.add(repairV);
        }
        model.addAttribute("record", list.size());
        model.addAttribute("repairList", repairs);
        model.addAttribute("openId", openId);
        return "weixin/repair-list";
    }

	@RequestMapping(value = "/repair/list")
	public String repairList(@RequestParam String code,  Model model) throws Exception{
        logger.info("repairList code:"+code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constants.APPID+"&secret="+Constants.SECRET+"&code="+code+"&grant_type=authorization_code";
        String responseEntityContent = RequestApp.request(url, null);
        logger.info("content:"+responseEntityContent);
        HashMap content = JsonUtil.fromJson(responseEntityContent, HashMap.class);
        logger.info("responseEntityContent map:"+content);
        String openId = "";
        if(content.get("openid") == null){
            return "weixin/error";
        }else{
            openId = String.valueOf(content.get("openid"));
            WxUser user =  wxUserService.getByOpenId(openId);
            if(user == null){
                return "weixin/error";
            }
            List<WxRoleMenu> list = wxRoleMenuService.findSelectedMenuList(user.getWxRole().getId());
            logger.info("[Click WxRoleMenu] " + list);
            if(list == null || list.size() == 0){
                return "weixin/error";
            }
            boolean flag = false;
            for(WxRoleMenu wxRoleMenu:list){
                if(wxRoleMenu.getWxMenuId() == 5){
                    flag = true;
                    break;
                }
            }
            if(!flag){
                return "weixin/error";
            }
        }
        logger.info("getListByOpenId openId:"+openId);
        List<Repair> list = repairService.getListByOpenId(openId);
        logger.info("getListByOpenId openId:"+list);
		List<RepairV> repairs = new ArrayList<RepairV>();
		for(Repair repair:list){
			RepairV repairV = new RepairV();
			BeanUtils.copyProperties(repair, repairV);
			repairV.setStatusStr(WorkStatus.getName(repairV.getStatus()));
			repairs.add(repairV);
		}
		model.addAttribute("record", list.size());
		model.addAttribute("repairList", repairs);
		model.addAttribute("openId", openId);
		return "weixin/repair-list";
	}

	@RequestMapping(value = "/repair/comment/{id}")
	public String comment(@PathVariable("id") int id,
			String openId, Model model) throws Exception {
		RepairV repairV = repairService.getRepair(id);
		repairV.setStatusStr(WorkStatus.getName(repairV.getStatus()));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(repairV.getRepairDate() != null){
            repairV.setRepairDateStr(sdf.format(repairV.getRepairDate()));
    	}
		if(repairV.getExpectedRepairTime() != null){
			repairV.setExpectedRepairTimeStr(sdf.format(repairV.getExpectedRepairTime()));
		}
		if(repairV.getPlanRepairTime() != null){
			repairV.setPlanRepairTimeStr(sdf.format(repairV.getPlanRepairTime()));
		}
		model.addAttribute("id", id);
		model.addAttribute("openId", openId);
		model.addAttribute("repair", repairV);
		if(repairV.getStatus() == WorkStatus.FINISHED.getValue()){
			return "weixin/comment";
		}else if(repairV.getStatus() == WorkStatus.COMMENT.getValue()){
			model.addAttribute("comment", commentRepairService.getByRepairId(repairV.getId()));
			return "weixin/comment-info";
		}
		return "weixin/repair-info";
	}

	@RequestMapping(value = "/repair/select/{id}")
	public String select(@PathVariable("id") int id,
                         Model model) throws Exception {
		RepairV repair = repairService.getRepair(id);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (repair.getPlanRepairTime() != null) {
			repair.setPlanRepairTimeStr(sdf.format(repair.getPlanRepairTime()));
		}
		if (repair.getMaintenanceTimeStart() != null) {
			repair.setMaintenanceTimeStartStr(sdf.format(repair
					.getMaintenanceTimeStart()));
		}
        if(repair.getCreateTime() != null){
            repair.setCreateTimeStr(sdf.format(repair.getCreateTime()));
        }
        if(repair.getExpectedRepairTime() != null){
            repair.setExpectedRepairTimeStr(sdf.format(repair.getExpectedRepairTime()));
        }
		model.addAttribute("repair", repair);
		if (repair.getStatus() == 2) {
			return "weixin/repair-start";
		} else if (repair.getStatus() == 3) {
			return "weixin/repair-complate";
		} else if (repair.getStatus() == 1 || repair.getStatus() == 8) {
			return "weixin/repair-select";
		}else{
			return "weixin/success";
		}
	}

	@RequestMapping(value = "/result")
	public String confirm() throws Exception {
		return "weixin/result";
	}

	@RequestMapping(value = "/repair/confirm/{id}")
	public String confirm(@PathVariable("id") int id, Model model) throws Exception {
        RepairV repairV = repairService.getRepair(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (repairV.getPlanRepairTime() != null) {
            repairV.setExpectedRepairTimeStr(sdf.format(repairV.getExpectedRepairTime()));
        }
        model.addAttribute("repair", repairService.getRepair(id));
		return "weixin/repair-confirm";
	}

	@RequestMapping(value = "/repair/feedback/{id}")
	public String feedback(@PathVariable("id") int id, Model model) throws Exception {
		model.addAttribute("repair", repairService.getRepair(id));
		return "weixin/repair-feedback";
	}

	@RequestMapping(value = "/repair/start/{id}")
	public String start(@PathVariable("id") int id, Model model) throws Exception {
		RepairV repair = repairService.getRepair(id);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (repair.getPlanRepairTime() != null) {
			repair.setPlanRepairTimeStr(sdf.format(repair.getPlanRepairTime()));
		}
		model.addAttribute("repair", repair);
		return "weixin/repair-start";
	}

	@RequestMapping(value = "/repair/complate/{id}")
	public String complate(@PathVariable("id") int id, Model model) throws Exception {
		RepairV repair = repairService.getRepair(id);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (repair.getMaintenanceTimeStart() != null) {
			repair.setMaintenanceTimeStartStr(sdf.format(repair
					.getMaintenanceTimeStart()));
		}
		model.addAttribute("repair", repair);
		return "weixin/repair-complate";
	}

    @RequestMapping(value = "/repair/openId")
    public String repairTemplate(@RequestParam String url, Model model) throws  Exception {
        model.addAttribute("url", url);
        model.addAttribute("appId", Constants.APPID);
        return "weixin/getOpenId";
    };
}
